<?php
namespace Apps\AppApi\Method\AppIndex;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\SysOpenCity;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\OmBanner;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\Advertisement;
use Apps\Common\Models\CosPointquestion;
use Phalcon\Mvc\Model;
use Apps\Common\Models\QuestionFollow;
use Apps\Common\Models\Question;
use Apps\Common\Models\CosPointBp;
use Apps\Common\Models\BeautyParlor;
use Apps\Common\Models\BeautyParlorTag;


/**
 * APP首页
 * @author      545
 * @date        2016年1月14日
 * @version     2.1.6
 * @copyright   Copyright 2015 meelier.com
 */
class AppIndex extends BaseMethod{
	
	public function run(){
		//判断城市是否开通 未开通城市  banner 广告位显示全国 美容院不显示
		
	    $banners = [];//首页banner
	    $questionlists = [];//首页推荐问答
	    
	    $city_code = $this->getDataItem('city_code',0);
	    $userid = $this->getDataItem('user_id',0);
	    
	    $is_open = SysOpenCity::findFirst(
	        [
	            'columns'=>"city_id",
	            'conditions' => "city_code = $city_code AND city_state = 1",
	        ]);
	    
	    $city_id = $is_open->city_id>0?$is_open->city_id:0;

	    $alllimit = $this->getConfig()->national;//属于全国的banner条数
	    //获取全国banner
	    $banners = $this->getBanner($alllimit, 0);
        
        //获取属于全国的广告
        $advert = $this->getAdvert(0,null,"addtime desc","position");
        
        //获取城市问答
        $limit_q = $this->getConfig()->question;
        $questionlists = $this->getQuestion(0, $limit_q,$userid,"sort DESC");
        
        //城市未开通
	    if (!$city_id){
	        foreach ($advert as $k=>$v){
	            $advert[$k]['advertisement_cover'] = PicUrl::ActivityCover($v['advertisement_cover'], $this->getDi());
	        }
	        
	        $lists['banner'] = $banners;
	        $lists['question'] = $questionlists;
	        $lists['parlors']=null;
	        $lists['adverts'] = empty($advert)?null:$advert;
	        
	        $this->setResult($lists);
	    }
	    else{

	        $citylimit = $this->getConfig()->city;
	        //获取城市banner
	        $citybanner = $this->getBanner($citylimit, $city_id);
	        if (count($citybanner)&&count($banners)){//如果全国banner不为空 切城市banner不为空
	            $banners = array_merge($banners,$citybanner);//合并数组
	        }
	        elseif (!count($banners)&&count($citybanner)){//全国banner为空 城市不为空
	            $banners = $citybanner;//返回城市banner
	        }
	        //获取城市问答
	        if(count($questionlists)<$limit_q){//如果全国的问答条数不足 则查询城市问答补充
	            $limit_c = $limit_q -count($questionlists);
	            $questionlist = $this->getQuestion($city_id, $limit_c,$userid,"sort DESC");
	            if (count($questionlists)&&count($questionlist)){
	               $questionlists = array_merge($questionlists,$questionlist);
	            }
	            elseif (!count($questionlists)&&count($questionlist)){
	                $questionlists = $questionlist;
	            }
	        }
	        
	        /*************************************************获取城市广告**********************************/
	        $pos_ids = array_column($advert, 'position');
	        
	        //如果没有全国的位置1的广告 则 查询是否有全国位置为1的广告
	        if (!in_array(1, $pos_ids)){
	            $temp = $this->getAdvert($city_id,"position = 1","addtime desc");
	            if (count($temp)&&count($advert)){
	                $advert = array_merge($advert,$temp);
	            }
	            elseif (!count($advert)&&count($temp)){
	                $advert = $temp;
	            }
	        }
	        //如果没有全国的位置2的广告 则 查询是否有全国位置为2的广告
	        if (!in_array(2, $pos_ids)){
	            $temp = $this->getAdvert($city_id,"position = 2","addtime desc");
	            if (count($temp)&&count($advert)){
	                $advert = array_merge($advert,$temp);
	            }
	            elseif (!count($advert)&&count($temp)){
	                $advert = $temp;
	            }
	        }
	        //如果没有全国的位置3的广告 则 查询是否有全国位置为3的广告
	        if (!in_array(3, $pos_ids)){
	            $temp = $this->getAdvert($city_id,"position = 3","addtime desc");
	            if (count($temp)&&count($advert)){
	                $advert = array_merge($advert,$temp);
	            }
	            elseif (!count($advert)&&count($temp)){
	                $advert = $temp;
	            }
	        }
	        $advert = $this->multi_array_sort($advert, 'position');
	        foreach ($advert as $k=>$v){
	            $advert[$k]['advertisement_cover'] = PicUrl::ActivityCover($v['advertisement_cover'], $this->getDi());
	        }
	        
	        /*************************************************美容院*****************************************/
	        //获取位置固定的美容院
	        $parlor = $this->getParlor($city_id, 3 ,"show_start_time DESC,id DESC","sort");
	        
	        $sortids = array_column($parlor, 'sort');
	        if (count($sortids)<3){//当固定位置的首页推荐美容院不足时，随机获取没有固定位置的推荐数据
	            $limit_r = 3-count($sortids);
	            $parlor_r = $this->getParlorRand($city_id,$limit_r);
	            if (count($parlor)&&count($parlor_r)){
	                $parlor = array_merge($parlor,$parlor_r);
	            }
	            elseif (!count($parlor)&&count($parlor_r)){
	                $parlor = $parlor_r;
	            }
	        }

	        $parlor = $this->multi_array_sort($parlor, 'sort');
	        foreach ($parlor as $k=>$v){
	            if ($v){
	                $parlor[$k]['cover'] = PicUrl::BeautyParlorCover($v['cover'], $this->getDi());
	                $parlor[$k]['medal_verify'] = \Apps\Common\Libs\BeautyParlor::getMedalVerify($v['bp_medal']);
	                unset($parlor[$k]['bp_medal']);
	                $tag = BeautyParlorTag::query()
    	                ->columns([
    	                'i.tag_title'
        	            ])
        	            ->leftJoin('Apps\Common\Models\BeautyParlorTagInfo','Apps\Common\Models\BeautyParlorTag.tag_id = i.tag_id','i')
        	            ->where('i.tag_state=1 and bp_id=:bid:')
        	            ->bind(['bid' => $v['id']])
        	            ->orderBy('sort desc,bp_tag_addtime asc')
        	            ->execute()->toArray();
	                $tags = array_column($tag,'tag_title');
	                $parlor[$k]['tags'] = empty($tags)?null:$tags;
	            }
	        }
            /***************************************************返回结果集******************************************/
	        $lists['banner'] = empty($banners)?null:$banners;
	        $lists['question'] = empty($questionlists)?null:$questionlists;
	        $lists['parlors'] = empty($parlor)?null:$parlor;
	        $lists['adverts'] = empty($advert)?null:$advert;
	         
	        $this->setResult($lists);
	    }
	}
	
	/********************************************************函数begin*****************************************************/
	/**
	 * 获取banner
	 * @date: 2016年1月22日 
	 * @author: 545
	 */
	private function getBanner($limit,$city_id){
	    
	    $banner = OmBanner::query()
	    ->columns(['banner_data'])
	    ->where('state = 1 AND banner_name =1 AND city_id = '.$city_id)
	    ->limit($limit,0)
	    ->orderBy('banner_update_time desc')
	    ->execute()->toArray();
	    
	    
	    
	    foreach ($banner as $k => $v){
	    
	        $data = json_decode($v['banner_data']);
	    
	        $temp[$k]['url'] =  PicUrl::DefaultPics($data->url,$this->getDi());
	        $temp[$k]['link_type'] = $data->link_type;
	        $temp[$k]['link_data'] = json_decode($data->link_data);
	    }
	    
	    return $temp;
	}
	/**
	 * 获取广告
	 * @date: 2016年1月22日 
	 * @author: 545
	 */
	private function getAdvert($city_id,$where=null,$order=null,$groupby=null){
	    
	    $where = empty($where)?"city_id = {$city_id} ":$where." AND city_id = {$city_id} ";
	    
	    if (!empty($groupby)){
	        $where .= " GROUP BY {$groupby}";
	    }
	    
	    $advert = Advertisement::query()
	    ->columns(['advertisement_id','advertisement_cover','advertisement_title','position','type','advertisement_intro','out_link'])
	    ->where($where)
	    ->orderBy($order)
	    ->execute()->toArray();
	    
	    return $advert;
	}
	
	/**
	 * 根据开通城市id获取问答列表
	 * @date: 2016年1月22日 
	 * @author: 545
	 */
	private function getQuestion($city_id,$limit,$userid=null,$order=null){
	    $questionlists = array();
	    $columns = [
	        'q.question_id',
	        'q.question_content',
	        'q.question_pics',
	        'q.question_tag',
	        'q.answer_num',
	        'q.question_browsers',
	        'q.is_expert_reply',
	        'q.question_addtime',
	        'u.user_id',
	        'u.user_nickname',
	        'u.user_cover',
	        'u.user_gender',
	    ];
	    //获取问答列表
	    $questionlist = CosPointquestion::query()
	    ->columns($columns)
	    ->join('\Apps\Common\Models\Question','q.question_id = \Apps\Common\Models\CosPointquestion.q_id','q')
	    ->join('\Apps\Common\Models\UserBase', 'u.user_id = q.user_id', 'u')
	    ->where('addr = :city_id:')
	    ->bind(['city_id'=>$city_id])
	    ->limit($limit,0)
	    ->orderBy($order)
	    ->execute()->toArray();
	    
	    $QuestionFollow = new QuestionFollow();
	    foreach ($questionlist as $k=>$val){
    	    // 是否收藏过
    	    if ($userid) {
    	        $questionlists[$k]['is_collection'] = $QuestionFollow->is_follow($val['question_id'], $userid);
    	    } else {
    	        $questionlists[$k]['is_collection'] = '0';
    	    }
    	    
    	   
	        $questionlists[$k]['question_id'] = $val['question_id'];
	        $questionlists[$k]['question_content'] = unserialize(base64_decode($val['question_content'])) ?: $val['question_content'];
	        $questionlists[$k]['question_pics'] =[];
	        if ($val['question_pics']) {
	            $question_pics = [];
	            foreach (json_decode($val['question_pics'], true) as $key => $value) {
	                $question_pics[] = PicUrl::Question($value, $this->getDi());
	            }
	            $questionlists[$k]['question_pics'] = $question_pics;
	        }
	        $questionlists[$k]['question_tag'] = $val['question_tag'] ? json_decode($val['question_tag'], true) : [];
	        $questionlists[$k]['answer_num'] = $val['answer_num'];
	        $questionlists[$k]['question_browsers'] = $val['question_browsers'];
	        $questionlists[$k]['is_expert_reply'] = $val['is_expert_reply'];
	        $questionlists[$k]['question_addtime'] = $val['question_addtime'];
	        $questionlists[$k]['user_id'] = $val['user_id'];
	        $questionlists[$k]['user_nickname'] = $val['user_nickname'];
	        $questionlists[$k]['user_cover'] = PicUrl::UserCover($val['user_cover'], $this->getDi());
	        $questionlists[$k]['user_gender'] = $val['user_gender'];
    	}

    	return $questionlists;
	}
	/**
	 * 获取美容院
	 * @date: 2016年1月22日 
	 * @author: 545
	 */
	private function getParlor($city_id,$limit,$order=null,$groupby=null){
	    
	    $where = '(show_start_time < now() AND show_end_time > now() and b.bp_state = 1 AND addr = :id:) OR ( ISNULL(show_start_time) AND ISNULL(show_end_time) AND sort IS NOT NULL and b.bp_state = 1 AND addr = :id:)';
	    if ($groupby){
	        $where .= " GROUP BY {$groupby}";
	    }
	    $parlor = CosPointBp::query()
	    ->columns(['b.bp_id id','b.bp_name name','sort','img_url cover','b.bp_address address','b.bp_medal'])
	    ->leftJoin('Apps\Common\Models\BeautyParlor','b.bp_id = Apps\Common\Models\CosPointBp.bp_id','b')
	    ->where($where)
	    ->bind(['id'=>$city_id])
	    ->limit($limit,0)
	    ->orderBy($order)
	    ->execute()->toArray();
	    
	    return $parlor;
	}
	
	private function getParlorRand($city_id,$limit){
	    $where = "ISNULL(show_start_time) AND ISNULL(show_end_time) and b.bp_state = 1 AND ISNULL(sort) AND addr = :id:";

	    $parlor = CosPointBp::query()
	    ->columns(['b.bp_id id','b.bp_name name','sort','img_url cover','b.bp_address address','b.bp_medal'])
	    ->leftJoin('Apps\Common\Models\BeautyParlor','b.bp_id = Apps\Common\Models\CosPointBp.bp_id','b')
	    ->where($where)
	    ->bind(['id'=>$city_id])
	    ->orderBy('rand()')
	    ->limit($limit,0)
	    ->execute()->toArray();
	    
	    return $parlor;
	}
	
	/**
	 * 二维数组根据key排序
	 * @date: 2016年1月25日 
	 * @author: 545
	 */
	private function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
	    if(is_array($multi_array)){
	        foreach ($multi_array as $row_array){
	            if(is_array($row_array)){
	                $key_array[] = $row_array[$sort_key];
	            }else{
	                return false;
	            }
	        }
	    }else{
	        return false;
	    }
	    array_multisort($key_array,$sort,$multi_array);
	    return $multi_array;
	}
} 